package com.lyf.app.interceptor;

import com.lyf.app.utils.sessionUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class LoginInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("token");
        String uri = request.getRequestURI();
        if (handler==null){
            response.setStatus(401);
        }else if (sessionUtils.get(header)==null){
            response.setStatus(403);
        }else {
            String[] split = header.split("-");
            if (Long.valueOf(split[2])-System.currentTimeMillis()>2*3600*100) {
                response.setStatus(403);
            }else {
                if (uri.equals("/appInfo/updateAppInfoStatus")){
                    if (split[3].equals("2")){
                        response.setStatus(403);
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
